import axios from 'axios';
import { Modal, notification } from 'ant-design-vue';
import router from '@/router/index.js';
import useUserStore from '@/stores/user.js';

const request = axios.create({
    baseURL: import.meta.env.VITE_GLOB_API_URL,
    timeout: 5 * 60 * 1000,
});

request.interceptors.request.use(
    (config) => {
        const userStore = useUserStore();
        const token = userStore.getToken();
        if (config.headers && token) {
            config.headers.set('Authorization', `Bearer ${token}`);
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    },
);

request.interceptors.response.use(
    (response) => {
        const { data, status, statusText } = response;
        if (response.config.responseType === 'blob') {
            return response;
        }
        if (response.config.responseType === 'arraybuffer') {
            return response.data;
        }
        if (data.code === 401) {
            Modal.confirm({
                title: '系统提示',
                content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
                centered: true,
                onOk() {
                    useUserStore()
                        .logout()
                        .then(() => {
                            location.href = '/login';
                        });
                },
                onCancel() {},
            });
        } else if (data.code === 403) {
            notification?.error({
                message: data?.msg,
                duration: 3,
            });
        } else if (data.code === 500) {
            notification?.error({
                message: data?.msg,
                duration: 3,
            });
            return Promise.reject(data?.msg);
        } else if (data.code !== 200) {
            notification?.error({
                message: data?.msg,
                duration: 3,
            });
        }
        return response.data;
    },
    (error) => {
        if (error.response) {
            const { data, status, statusText } = error.response;
            notification?.error({
                message: '服务器内部错误',
                duration: 3,
            });
        }
        return Promise.reject(error);
    },
);

export default request;
